package _thread_lock._threadpool;

import _thread_lock._threadpool._denypolicy.DenyPolicy;
import _thread_lock._threadpool._denypolicy.DiscardDenyPolicy;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: huangya
 * @Date: 2020/10/14
 * @Description:
 */
public class BasicThreadPool extends Thread implements ThreadPool {

    //初始化线程数量
    private final int initSize;

    //线程池最大线程数量
    private final int maxSize;

    //线程池核心线程数量
    private final int coreSize;

    //当前活跃的线程数量
    private int activeCount;

    //创建线程所需的工厂
    private final ThreadFactory threadFactory;

    //任务队列
    /** Runnable队列 */
    private final RunnableQueue runnableQueue;

    //线程池是否需要被shutdown
    private volatile boolean isShutdown = false;

    //工作线程队列
    /** ThreadTask队列 */
    private final Queue<ThreadTask> threadQueue = new ArrayDeque<>();

    private final static DenyPolicy DEFAULT_DENY_POLICY = new DiscardDenyPolicy();

    private final static ThreadFactory DEFAULT_THREAD_FACTORY = new DefaultThreadFactory();

    private final long keepAliveTime;

    private final TimeUnit timeUnit;

    public BasicThreadPool(int initSize, int maxSize, int coreSize, int queueSize) {
        this(initSize, maxSize, coreSize, DEFAULT_THREAD_FACTORY, queueSize, DEFAULT_DENY_POLICY, 10, TimeUnit.SECONDS);
    }

    public BasicThreadPool(int initSize, int maxSize, int coreSize, ThreadFactory threadFactory,
                           int queueSize, DenyPolicy denyPolicy, long keepAliveTime, TimeUnit timeUnit) {
        this.initSize = initSize;
        this.maxSize = maxSize;
        this.coreSize = coreSize;
        this.threadFactory = threadFactory;
        this.runnableQueue = new LinkedRunnableQueue(queueSize, denyPolicy, this);
        this.keepAliveTime = keepAliveTime;
        this.timeUnit = timeUnit;
        this.init();
    }

    /**
     * 1、启动线程池，调用线程池run()方法
     * 2、循环调用newThread()方法创建线程，并启动线程
     */
    private void init(){
        start();
        for(int i=0; i<initSize; i++){
            newThread();
        }
    }

    /**
     * 创建线程，启动线程
     */
    private void newThread(){
        /** internalTask对象的run方法会【循环】从runnableQueue队列中获取Runnable对象，并执行Runnable对象的run方法。 */
        InternalTask internalTask = new InternalTask(runnableQueue);
        /** 创建目标对象为internalTask的线程 */
        Thread thread = this.threadFactory.createThread(internalTask);
        ThreadTask threadTask = new ThreadTask(thread, internalTask);
        /** 搜集管理threadTask对象 */
        threadQueue.offer(threadTask);
        this.activeCount++;
        thread.start();
    }

    /**
     * 移除线程，停止线程
     */
    private void removeThread(){
        ThreadTask threadTask = threadQueue.remove();
        threadTask.internalTask.stop();
        this.activeCount--;
    }

    @Override
    public void shutdown() {
        synchronized (this){
            if(isShutdown){
                return;
            }
            isShutdown = true;
            threadQueue.forEach(threadTask -> {
                threadTask.internalTask.stop();
                threadTask.thread.interrupt();
            });
            this.interrupt();
        }
    }

    @Override
    public void execute(Runnable runnable) {
        if(this.isShutdown()){
            throw new IllegalStateException("The thread pool is destory");
        }
        this.runnableQueue.offer(runnable);
    }

    @Override
    public void run() {
        while (!isShutdown && !isInterrupted()){
            try {
                timeUnit.sleep(keepAliveTime);
            } catch (InterruptedException e){
                isShutdown = true;
                break;
            }
            synchronized (this){
                if(isShutdown){
                    break;
                }
                if(runnableQueue.size()>0 && activeCount < coreSize){
                    for(int i=initSize; i<coreSize; i++){
                        newThread();
                    }
                    continue;
                }
                if(runnableQueue.size()>0 && activeCount<maxSize){
                    for(int i=coreSize; i<maxSize; i++){
                        newThread();
                    }
                }
                if(runnableQueue.size()==0 && activeCount > coreSize){
                    for(int i=coreSize; i<activeCount; i++){
                        removeThread();
                    }
                }
            }
        }
    }


    @Override
    public int getInitSize() {
        if(isShutdown){
            throw new IllegalStateException("The thread pool is destory");
        }
        return this.initSize;
    }

    @Override
    public int getMaxSize() {
        if(isShutdown){
            throw new IllegalStateException("The thread pool is destory");
        }
        return this.maxSize;
    }

    @Override
    public int getCoreSize() {
        if(isShutdown){
            throw new IllegalStateException("The thread pool is destory");
        }
        return this.coreSize;
    }

    @Override
    public int getQueueSize() {
        if(isShutdown){
            throw new IllegalStateException("The thread pool is destory");
        }
        return runnableQueue.size();
    }

    @Override
    public int getActiveCount() {
        synchronized (this) {
            return this.activeCount;
        }
    }

    @Override
    public boolean isShutdown() {
        return this.isShutdown;
    }


    /**
     * 线程、内部任务
     */
    private static class ThreadTask{

        Thread thread;

        InternalTask internalTask;

        public ThreadTask(Thread thread, InternalTask internalTask) {
            this.thread = thread;
            this.internalTask = internalTask;
        }
    }

    /**
     * 默认线程工厂
     */
    private static class DefaultThreadFactory implements ThreadFactory {

        private static final AtomicInteger GROUP_COUNTER = new AtomicInteger(1);

        private static final ThreadGroup group = new ThreadGroup("MyThreadPool-" + GROUP_COUNTER.getAndDecrement());

        private static final AtomicInteger COUNTER = new AtomicInteger(0);

        @Override
        public Thread createThread(Runnable runnable) {
            return new Thread(group, runnable, "thread-pool-" + COUNTER.getAndDecrement());
        }
    }
}
